<template>
  <div class="container">
    <div ref="searchRef">
      <el-form :inline="true" :model="formInline" class="grids gridColumns6">
        <el-form-item :label="item.label" v-for="(item,index) in searchParams" :key="index">
          <el-select @change="onSubmit" v-model="formInline[item.value]" filterable :placeholder="item.placeholder" v-if="item.type ==='select'">
            <el-option v-for="(item,index) in item.options" :key="index" :label="item" :value="item" />
          </el-select>
          <dictSelect v-model="formInline[item.value]" :dictCode="item.code" :multiple="item.multiple==1" v-else-if="item.type === 'dict'"></dictSelect>
          <el-input v-model="formInline[item.value]" :placeholder="item.placeholder" clearable v-else @change="onSubmit" />
        </el-form-item>
        <el-form-item>
          <el-dropdown>
            <el-button type="primary">操作</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="batchUpdateUserData(1)" v-if="counter.isAdmin">批量更新用户数据</el-dropdown-item>
                <el-dropdown-item :disabled="!selectArr.length" @click="exportExcel">导出</el-dropdown-item>
                <el-dropdown-item @click="toDel" :disabled="!selectArr.length">注销用户信息</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <!-- <el-button type="primary" @click="onSubmit">查询</el-button> -->
          <el-button @click="init" style="margin-left: 10px;">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="tableLoading" :data="tableData.rows" :max-height="tableMaxHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="baseInfo.name" label="姓名" />
      <el-table-column prop="mobile" label="联系方式" width="120" />
      <el-table-column prop="baseInfo.identityCard" label="身份证" width="170" />
      <el-table-column prop="baseInfo.email" label="邮箱" width="240" show-overflow-tooltip>
        <template #default="scope">
          {{scope.row.baseInfo.email||'-'}}
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.education" label="最高学历" width="180">
        <template #default="scope">
          {{scope.row.baseInfo.education||'-'}}
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.graduationMajor" label="毕业专业" width="200" show-overflow-tooltip>
        <template #default="scope">
          {{scope.row.baseInfo.graduationMajor||'-'}}
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.workYears" label="累计工作年限 " width="130">
        <template #default="scope">
          {{scope.row.baseInfo.workYears||'-'}}
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.employed_Status" label="就业状态 " width="130">
        <template #default="scope">
          {{scope.row.baseInfo.employed_Status||'-'}}
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.enterprise" label="所在企业名称" width="300" show-overflow-tooltip>
        <template #default="scope">
          {{counter.showEnterprise(scope.row.baseInfo,"enterprise")}}
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.enterpriseTax" label="所在企业税号" width="200" show-overflow-tooltip>
        <template #default="scope">
          {{counter.showEnterprise(scope.row.baseInfo,"enterpriseTax")}}
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.enterpriseJurisdiction" label="所在企业区属" width="220">
        <template #default="scope">
          {{scope.row.baseInfo.enterpriseJurisdiction||'-'}}
        </template>
      </el-table-column>
      <el-table-column label="学员标签" width="200" align="center">
        <template #default="scope">
          <el-popover placement="right" :width="300" trigger="click" v-if="proxy.$utils.isNumber(tags_format(scope.row))">
            <template #reference>
              <el-button type="primary" text>
                {{tags_format(scope.row)}}
              </el-button>
            </template>
            <div>
              <div v-for="(item,index) in scope.row.baseInfo.tags" :key="index" class="tags-item">{{item}}</div>
            </div>
          </el-popover>
          <el-tooltip class="box-item" effect="dark" :content="tags_format(scope.row)" placement="top-start" v-else-if="tags_format(scope.row).length>10">
            <div>{{ proxy.$utils.truncateString(tags_format(scope.row), 10)}}</div>
          </el-tooltip>
          <div v-else>{{tags_format(scope.row)}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="学员来源" width="250" show-overflow-tooltip>
        <template #default="scope">
          <el-popover placement="right" :width="200" trigger="click" v-if="proxy.$utils.isNumber(form_format(scope.row))">
            <template #reference>
              <el-button type="primary" text>{{form_format(scope.row)}}</el-button>
            </template>
            <el-table :data="scope.row.studentSourceList">
              <el-table-column prop="source" label="学员来源" />
            </el-table>
          </el-popover>
          <div v-else>{{form_format(scope.row)}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="微信昵称" width="120">
        <template #default="scope">
          <div v-if="scope.row.nickname">
            <el-tooltip v-if="scope.row.nickname.length>6" class="box-item" effect="dark" :content="scope.row.nickname" placement="top-start">
              <div>{{proxy.$utils.truncateString(scope.row.nickname,6)}}</div>
            </el-tooltip>
            <div v-else>{{scope.row.nickname}}</div>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="登录方式" width="150">
        <template #default="scope">
          {{login_type_format(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column prop="baseInfo.updateUser" label="操作人" width="100" />
      <el-table-column fixed="right" label="操作" width="60" align="center">
        <template #default="scope">
          <div class="button" @click="handleClick(scope.row,1)">编辑</div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-if="tableData['total']" :total="tableData['total']" v-model:page="formInline.pageIndex" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <el-dialog v-model="dialogVisible" title="编辑用户信息" width="700" :before-close="handleClose">
      <el-form :model="model" label-width="100" class="edit-form">
        <el-form-item label="姓名">
          <el-input v-model="model.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="model.mobile" placeholder="请输入联系方式" clearable />
        </el-form-item>
        <el-form-item label="身份证">
          <el-input v-model="model.identityCard" placeholder="请输入身份证" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="model.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="毕业专业">
          <el-input v-model="model.graduationMajor" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="累计工作年限">
          <el-select v-model="model.workYears" filterable placeholder="请选择累计工作年限">
            <el-option v-for="(item,index) in workYears.split(',')" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在企业">
          <el-select @change="handleChange" v-model="model.enterprise" filterable remote reserve-keyword placeholder="请选择所在企业" :remote-method="remoteMethod" :loading="loading">
            <el-option v-for="(item,index) in enterpriseList" :key="index" :label="item.qymc" :value="item.qymc" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业税号">
          <el-input v-model="model.enterpriseTax" placeholder="请输入企业税号" clearable disabled />
        </el-form-item>
        <el-form-item label="企业区属">
          <el-input v-model="model.enterpriseJurisdiction" placeholder="请输入企业区属" clearable disabled />
        </el-form-item>
        <el-form-item label="学员标签">
          <dictSelect v-model="model.tags" dictCode="user_tag" multiple="1"></dictSelect>
        </el-form-item>
        <el-form-item label="学员来源">
          <el-input disabled :value="studentSource" placeholder="请输入学员来源" clearable />
        </el-form-item>
        <el-form-item label="学员身份证" v-if="model.identification_scancopy">
          <div>
            <el-button type="primary" @click="proxy.$refs.idCardRef.open()">上传附件</el-button>
            <div v-if="proxy.$utils.isString(model.identification_scancopy)">
              <div v-for="(item,index) in model.identification_scancopy.split(',')" :key="index">
                <el-link type="primary" target="_blank" :href="item">{{model.name}}身份证{{index+1}}</el-link>
              </div>
            </div>
            <div v-else>
              <div v-for="(item,index) in model.identification_scancopy" :key="index">
                <el-link type="primary" target="_blank" :href="item.path">{{model.name}}身份证{{index+1}}</el-link>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="毕业证书" v-if="model.certificate_scancopy">
          <div>
            <el-button type="primary" @click="proxy.$refs.certificateRef.open()">上传附件</el-button>
            <div v-if="proxy.$utils.isString(model.certificate_scancopy)">
              <div v-for="(item,index) in model.certificate_scancopy.split(',')" :key="index">
                <el-link type="primary" target="_blank" :href="item">{{model.name}}毕业证书{{index+1}}</el-link>
              </div>
            </div>
            <div v-else>
              <div v-for="(item,index) in model.certificate_scancopy" :key="index">
                <el-link type="primary" target="_blank" :href="item.path">{{model.name}}毕业证书{{index+1}}</el-link>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="save" :loading="loading">
            确 认
          </el-button>
        </div>
      </template>
      <FileUploader v-model="model.identification_scancopy" ref="idCardRef"></FileUploader>
      <FileUploader v-model="model.certificate_scancopy" ref="certificateRef"></FileUploader>
    </el-dialog>

    <el-dialog v-model="visible" title="初始化用户登录信息" width="500" :before-close="onClose">
      <el-radio-group v-model="initType.type">
        <el-radio label="1">PC</el-radio>
        <el-radio label="2">小程序</el-radio>
      </el-radio-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onClose">取 消</el-button>
          <el-button type="primary" @click="submit">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <input type="file" @change="handleFileUpload" v-show="false" ref="inputFile" />

    <input type="file" @change="handleFileImport" v-show="false" ref="fileClick" />

    <!-- 导入失败的原因 -->
    <studentImportError ref="studentImportErrorRef"></studentImportError>
  </div>
</template>

<script setup lang="ts">
import studentImportError from "@/views/order/components/studentImportError.vue";
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();

let workYears = ref(
  "应届毕业年,不满1年,满1年,满2年,满3年,满4年,满5年,满6年,满7年,满8年,满9年,满10年及以上"
);
let visible = ref(false);
let selectArr = ref([]); //选中的数组
let tableData = ref({});
let updateUserInfo = false; //更新用户数据
let formInline = ref({
  pageIndex: 1,
  pageSize: 50,
  name: "",
  nickname: "",
  mobile: "",
  identityCard: "",
  email: "",
  education: "",
  graduationMajor: "",
  workYears: "",
  enterprise: "",
  enterpriseTax: "",
  enterpriseJurisdiction: "",
  tags: [],
  studentSourceList: "",
});
let searchParams = ref([
  { label: "姓名", value: "name", type: "input", placeholder: "请输入姓名" },
  {
    label: "联系方式",
    value: "mobile",
    type: "input",
    placeholder: "请输入联系方式",
  },
  {
    label: "身份证",
    value: "identityCard",
    type: "input",
    placeholder: "请输入身份证",
  },
  // { label: "邮箱", value: "email", type: "input", placeholder: "请输入邮箱" },
  {
    label: "最高学历",
    value: "education",
    type: "input",
    placeholder: "请输入最高学历",
  },
  {
    label: "毕业专业",
    value: "graduationMajor",
    type: "input",
    placeholder: "请输入毕业专业",
  },
  {
    label: "累计工作年限",
    value: "workYears",
    type: "select",
    placeholder: "请选择累计工作年限",
    options: [
      "应届毕业年",
      "不满1年",
      "满1年",
      "满2年",
      "满3年",
      "满4年",
      "满5年",
      "满6年",
      "满7年",
      "满8年",
      "满9年",
      "满10年及以上",
    ],
  },
  {
    label: "所在企业",
    value: "enterprise",
    type: "input",
    placeholder: "请输入所在企业",
  },
  {
    label: "所在区属",
    value: "enterpriseJurisdiction",
    type: "input",
    placeholder: "请输入所在区属",
  },
  {
    label: "学员标签",
    value: "tags",
    type: "dict",
    placeholder: "请选择学员标签",
    code: "user_tag",
    multiple: 1,
  },
  {
    label: "学员来源",
    value: "studentSourceList",
    type: "dict",
    placeholder: "请选择学员来源",
    code: "user_source",
    multiple: 0,
  },
  {
    label: "微信昵称",
    value: "nickname",
    type: "input",
    placeholder: "请输入微信昵称",
  },
]);

let isShow = ref(true);
let dialogVisible = ref(false);
let loading = ref(false);
let tableLoading = ref(false); //列表加载
let importLoading = ref(false); //导入模板loading
let model = ref({
  userId: "",
  name: "",
  mobile: "",
  identityCard: "",
  email: "",
  education: "",
  graduationMajor: "",
  workYears: "",
  enterprise: "",
  enterpriseTax: "",
  enterpriseJurisdiction: "",
  tags: [],
  identification_scancopy: "",
  certificate_scancopy: "",
});
let enterpriseList = ref([]);
let studentSource = ref(""); //编辑的时候展示一下学员来源
let initType = ref({
  _id: "",
  type: "1",
});
let searchHeight = ref(0);

onMounted(async () => {
  getInfo();
  searchHeight.value = proxy.$refs.searchRef.offsetHeight;
});

let tableMaxHeight = computed(() => {
  let hei =
    window.innerHeight - 84 - counter.pageHeight - 55 - searchHeight.value;
  return `${hei}px`;
});

//导出
async function exportExcel() {
  try {
    importLoading.value = true;
    // let list = await proxy.$apis.student({
    //   type: "query",
    //   data: formInline.value,
    // });
    let list = proxy.$utils.deepcopy(selectArr.value);
    let data = [];
    list.forEach((element) => {
      data.push({
        姓名: element.baseInfo.name || "-",
        联系方式: element.mobile || "-",
        身份证: element.baseInfo.identityCard || "-",
        邮箱: element.baseInfo.email || "-",
        最高学历: element.baseInfo.education || "-",
        毕业专业: element.baseInfo.graduationMajor || "-",
        累计工作年限: element.baseInfo.workYears || "-",
        所在企业: element.baseInfo.enterprise || "-",
        企业税号: element.baseInfo.enterpriseTax || "-",
        企业区属: element.baseInfo.enterpriseJurisdiction || "-",
        学员标签: getString(element.baseInfo.tags || [], ""),
        学员来源: getString(element.studentSourceList, "source"),
        微信昵称: element.nickname || "-",
      });
    });
    function getString(arr, fileName) {
      if (!arr) return "";
      if (arr.length == 0) return "";
      if (fileName) {
        return arr.map((item) => item[fileName]).join(",");
      } else {
        return arr.toString();
      }
    }
    let cols = []; //设置表头样式
    list.forEach((element) => {
      cols.push({ wch: 20 });
    });
    let query = { jsonData: data, cols };
    await proxy.$utils.exportToExcel(query, "学员信息");
  } catch (error) {
    console.log("error", error);
  } finally {
    importLoading.value = false;
  }
}

async function clearAll() {
  let resp = await proxy.$utils.confirmTips("确认清空全部数据?");
  if (!resp) return;
  await proxy.$apis.student({
    type: "clearAll",
  });
  getInfo();
  proxy.$utils.showToast("清空成功");
}

function batchUpdateUserData(num) {
  if (num == 1) {
    updateUserInfo = true;
  } else {
    updateUserInfo = false;
  }
  proxy.$refs.fileClick.click();
}

async function submit() {
  try {
    let resp = await proxy.$utils.confirmTips("确认初始化?");
    if (!resp) return;
    loading.value = true;
    await proxy.$apis.student({ type: "initLogin", data: initType.value });
    proxy.$utils.showToast("初始化登录成功");
    onClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function onClose() {
  initType.value = {
    _id: "",
    type: "1",
  };
  visible.value = false;
  getInfo();
}

async function toDel() {
  let resp = await proxy.$utils.confirmTips("确认删除?");
  if (!resp) return;
  for (let index = 0; index < selectArr.value.length; index++) {
    const element = selectArr.value[index];
    await proxy.$apis.student({
      type: "del",
      data: { _id: element._id },
    });
  }
  proxy.$utils.showToast("删除成功");
  selectArr.value = [];
  getInfo();
}

function form_format(row) {
  if (!row.studentSourceList) return;
  let arr = row.studentSourceList || [];
  if (arr.length == 1) {
    return arr[0].source;
  } else if (!arr.length) {
    return "";
  } else {
    return arr.length;
  }
}

function handleSelectionChange(val) {
  selectArr.value = val;
}

function login_type_format(row) {
  let arr = [];
  if (row.hasOwnProperty("pc") && row.pc.openid) arr.push("PC");
  if (row.hasOwnProperty("h5") && row.h5.openid) arr.push("H5");
  if (row.hasOwnProperty("wx") && row.wx.openid) arr.push("小程序");
  return arr.join("、");
}

function tags_format(obj) {
  if (!obj.hasOwnProperty("baseInfo")) return;
  let str;
  if (obj.baseInfo.tags) {
    let tags = [...obj.baseInfo.tags];
    if (tags.length == 1) {
      str = tags[0];
    } else if (tags.length == 0) {
      str = "-";
    } else {
      str = tags.length;
    }
  } else {
    str = "-";
  }
  return str;
}

function handleClick(row, num) {
  switch (num) {
    case 1:
      if (row.hasOwnProperty("baseInfo")) {
        model.value = proxy.$utils.formatFunction(row.baseInfo, {
          ...model.value,
        });
        if (row.studentSourceList && row.studentSourceList.length) {
          let arr = [];
          row.studentSourceList.forEach((element) => {
            arr.push(element.source);
          });
          studentSource.value = arr.toString();
        }
      }
      model.value.userId = row._id;
      console.log("学员信息", model.value);
      dialogVisible.value = true;
      break;
    case 2:
      initType.value._id = row._id;
      visible.value = true;
      break;
    default:
      break;
  }
}

async function getInfo() {
  try {
    tableLoading.value = true;
    tableData.value = await proxy.$apis.student({
      type: "list",
      data: formInline.value,
    });
  } catch (error) {
  } finally {
    tableLoading.value = false;
  }
}

const remoteMethod = async (query: string) => {
  if (!query) return;
  try {
    loading.value = true;
    enterpriseList.value = await proxy.$apis.autoMatchCompany({
      key: query,
    });
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

function handleChange(e) {
  let index = proxy.$utils.findIndexByField(enterpriseList.value, "qymc", e);
  if (index != -1) {
    // model.value.enterpriseInfo = enterpriseList.value[index];
    let info = enterpriseList.value[index];
    model.value.enterpriseTax = info.nsrsbh;
    //所属区属
    let resp = extractAddressInfo(info.dzdh);
    model.value.enterpriseJurisdiction =
      resp.province + resp.city + resp.district;
  }

  function extractAddressInfo(address) {
    const regex = /(.*省|.*自治区)?(.*市)?(.*区|.*县)?/;
    const matches = address.match(regex);

    let province = matches[1] ? matches[1].trim() : "";
    let city = matches[2] ? matches[2].trim() : "";
    let district = matches[3] ? matches[3].trim() : "";

    return { province, city, district };
  }
}

async function save() {
  try {
    loading.value = true;
    model.value.updateUser = counter.updateUser;
    model.value["from"] = "web-edit-info";
    await proxy.$apis.student({
      data: model.value,
      type: "perfect",
    });
    proxy.$utils.showToast("保存成功");
    handleClose();
  } catch (error) {
    console.log("啥问题", error);
  } finally {
    loading.value = false;
  }
}

function handleClose() {
  model.value = {
    userId: "",
    name: "",
    mobile: "",
    identityCard: "",
    email: "",
    education: "",
    graduationMajor: "",
    workYears: "",
    enterprise: "",
    enterpriseTax: "",
    enterpriseJurisdiction: "",
    tags: [],
    certificate_scancopy: "",
    identification_scancopy: "",
  };
  getInfo();
  studentSource.value = "";
  dialogVisible.value = false;
}

function onSubmit() {
  formInline.value.pageIndex = 1;
  getInfo();
}

function init() {
  formInline.value = {
    pageIndex: 1,
    pageSize: 50,
    nickname: "",
    mobile: "",
    identityCard: "",
    email: "",
    education: "",
    graduationMajor: "",
    workYears: "",
    enterprise: "",
    enterpriseTax: "",
    enterpriseJurisdiction: "",
    tags: [],
    studentSourceList: "",
  };
  getInfo();
}

async function handleFileUpload(event) {
  let file = {
    name: "",
    path: "",
    type: "student",
  };
  const files = event.target.files;
  file.name = files[0].name;
  file.path = await counter.qiniuUpload(files[0]);
  await proxy.$apis.fileTemplate({
    data: file,
    type: "update",
  });
  proxy.$utils.showToast("上传成功");
}

async function downLoadTemplate() {
  counter.downLoadTemplate("student", "学员导入模板");
}

async function handleFileImport(event) {
  try {
    importLoading.value = true;
    const files = event.target.files;
    let file = files[0];
    let resp = await proxy.$utils.fileToJson(file);
    let list = [];

    for (let index = 0; index < resp.length; index++) {
      const element = resp[index];
      if (index) {
        if (!proxy.$utils.isPoneAvailable(element[1]))
          return proxy.$utils.showToast(`${element[0]}手机号格式错误`, 0);
        list.push({
          name: element[0],
          mobile: element[1],
          identityCard: element[2],
          email: ["/", "-"].includes(element[3]) ? "" : element[3],
          education: element[4],
          graduationMajor: element[5],
          workYears: element[6],
          employed_Status: element[7],
          enterprise: element[8],
          enterpriseTax: element[9],
          enterpriseJurisdiction: element[10],
          tags: ["/", "-"].includes(element[11]) ? "" : element[11],
          studentSourceList: ["/", "-"].includes(element[12])
            ? ""
            : element[12],
          updateUser: counter.updateUser, //更新用户
        });
      }
    }
    let type = "student";
    if (updateUserInfo) type = "studentUpdate";
    let { errorList } = await proxy.$apis.fileTemplate({
      data: { type, list },
      type: "import",
    });
    if (errorList.length) {
      proxy.$refs.studentImportErrorRef.open(errorList);
    } else {
      init();
      proxy.$utils.showToast("导入成功");
    }
  } catch (error) {
    console.log("遇到什么问题了吗", error);
  } finally {
    event.target.value = "";
    importLoading.value = false;
  }
}

watch(
  () => [formInline.value.tags, formInline.value.studentSourceList],
  (newValue, oldValue) => {
    if (newValue) onSubmit();
  },
  { deep: true, immediate: true }
);
</script>



<style lang="scss" scoped>
.container {
  margin: 20px;
}
.actionBtn {
  margin-bottom: 15px;
}
.edit-form {
  max-height: 60vh;
  overflow-y: auto;
}
</style>



